/**
 *	@author btan
 *	@email: btan@tma.com.vn - anbtan@gmail.com
 */
package com.vital.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class HttpService {
	URL feedURL;
	
	public String getStringJson(String url) {
		//---TMA Proxy test---
//		readJSON(url);
//		return getInputStream();
		
		StringBuilder sb = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(content));
				String line = "";
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			} else {
				Log.e("HttpService", "Failed to download");
			}
			
		} catch (ClientProtocolException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	
	
	public void readJSON(String urlString) {
		try {
			URL url = new URL(urlString);
			this.feedURL = new URL(url.getProtocol(), "10.10.10.10", 8080, urlString);
			//this.feedURL = url;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public String getInputStream() {
		StringBuilder sb = new StringBuilder();
		try {
			InputStream content = this.feedURL.openConnection().getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(content));
			String line;
			while((line = br.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
}
